package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.Commend;
import model.SMS;

public class CommendMod {
	Connection connection;
	public static CommendMod isntanceCM;
	public static CommendMod getIsntance(){
		if(isntanceCM == null){
			isntanceCM = new CommendMod();
		}
		return isntanceCM;
	}
	public boolean isCmid(int cmid){
		boolean result = false;
		connection = DB_Connection.getIsntance().getConnection();
		try {
			String sql = "SELECT * FROM commend WHERE cmid = ? ";
			PreparedStatement sqli = connection.prepareStatement(sql);
			sqli.setInt(1, cmid);
			int n = sqli.executeUpdate();
			if(n > 0) result = true ;
			sqli.close();
			connection.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
	public boolean add(Commend cm)  {
		boolean result = false;
		connection = DB_Connection.getIsntance().getConnection();
		PreparedStatement sqli = null;
		String sql = "INSERT INTO commend (uid, contents, datetime) VALUES (? , ? , NOW())";
		try {
			sqli = connection.prepareStatement(sql);
			sqli.setInt(1, cm.getUid());
			sqli.setString(2, cm.getContents());
			int n = sqli.executeUpdate();
			if (n > 0)
				result = true;
			sqli.close();
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	public Commend getCommend(int cmid){
		Commend result = null;
		connection = DB_Connection.getIsntance().getConnection();
		try {
			String sql = "SELECT * FROM commend WHERE cmid = ? ";
			PreparedStatement sqli = connection.prepareStatement(sql);
			sqli.setInt(1, cmid);
			ResultSet rs = sqli.executeQuery();
			while(rs.next()){
				result = new Commend(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getDate(4));
			}
			sqli.close();
			connection.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
	public Commend getCommendByUid(int uid){
		Commend result = null;
		connection = DB_Connection.getIsntance().getConnection();
		try {
			String sql = "SELECT * FROM commend WHERE uid = ? ";
			PreparedStatement sqli = connection.prepareStatement(sql);
			sqli.setInt(1, uid);
			ResultSet rs = sqli.executeQuery();
			while(rs.next()){
				result = new Commend(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getDate(4));
			}
			sqli.close();
			connection.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
}
